package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.CoreServiceImpl;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.dao.ChapterDao;
import com.jinzhi.jzweb.domain.ChapterDO;
import com.jinzhi.jzweb.pojo.entity.ChapterDocument;
import com.jinzhi.jzweb.pojo.request.ChapterRequest;
import com.jinzhi.jzweb.service.ChapterDocumentService;
import com.jinzhi.jzweb.service.ChapterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 章节表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Service
public class ChapterServiceImpl extends CoreServiceImpl<ChapterDao, ChapterDO> implements ChapterService {

    private final ChapterDocumentService documentService;

    public ChapterServiceImpl(ChapterDocumentService documentService) {
        this.documentService = documentService;
    }

    @Override
    public List<Map> selChapterList(Long id){
        return this.baseMapper.selChapterList(id);
    }

    @Override
    @Transactional
    public Result insertOrUpdateCharpter(ChapterDO chapterDO) {
        //新增章节信息
        boolean aBoolean = this.insertOrUpdate(chapterDO);
        if(aBoolean == false){
            return Result.fail();
        }
        boolean bBoolea = true;
        if(!chapterDO.getChapterDocuments().isEmpty()){
            //新增章节文件信息
            for (int i = 0; i < chapterDO.getChapterDocuments().size(); i++) {
                chapterDO.getChapterDocuments().get(i).setChapterId(chapterDO.getId());
            }
            bBoolea = documentService.insertOrUpdateBatch(chapterDO.getChapterDocuments());
        }
        if (!bBoolea){
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    @Transactional
    public Result batchRemoveCharpter(List<ChapterDO> ids) {
        //删除章节文件信息
        ids.forEach(a -> {
            documentService.delete(new EntityWrapper<ChapterDocument>().eq("chapter_id",a.getId()));
        });
        List<Long> pids = ids.stream().map(ChapterDO::getId).collect(Collectors.toList());
        //删除章节信息
        return this.deleteBatchIds(pids) ? Result.ok() : Result.fail();
    }

    @Override
    public Result getChapter(ChapterRequest request) {
        Page<ChapterDO> page = new Page<ChapterDO>(request.getCurrent(),request.getSize());
        //根据资源id查询章节信息
        List<ChapterDO> list =  this.selectList(new EntityWrapper<ChapterDO>().eq("courses_id",request.getCoursesId())
                .like(StringUtil.isNotNull(request.getName()),"name",request.getName())
                .orderBy("creater_date",false));
        if(list.isEmpty()){
            return Result.ok(page);
        }
        list = list.stream().sorted(Comparator.comparing(ChapterDO::getSort,Comparator.nullsFirst(Integer::compareTo).reversed())).collect(Collectors.toList());
        //根据资源id查询章节文件信息
        List<ChapterDocument> documents =  documentService.selectList(new EntityWrapper<ChapterDocument>()
                .eq("courses_id",request.getCoursesId()));
        if(!documents.isEmpty()) {
            //给章节匹配资源信息
            list.forEach(a ->{
              a.setChapterDocuments(documents.stream().filter(b-> b.getChapterId().equals(a.getId())).collect(Collectors.toList()));
            });
        }
        //筛选出根目录章节信息
        List<ChapterDO>  isRootList = list.stream().filter(a -> a.getIsRoot()==1).collect(Collectors.toList());
        if(request.getType()==1){
            //筛选出非根目录章节,第一层子节点信息
            List<ChapterDO>  notRootList1 = list.stream().filter(a -> a.getIsRoot()!=1 &&  a.getLevel() == 1).collect(Collectors.toList());
            //筛选出非根目录章节,第二层子节点信息
            List<ChapterDO>  notRootList2 = list.stream().filter(a -> a.getIsRoot()!=1 &&  a.getLevel() == 2).collect(Collectors.toList());
            //匹配二层数据至一层
            notRootList1.forEach(a -> {
                a.setChapterDOS(notRootList2.stream().filter(b -> b.getParentId().equals(a.getId())).collect(Collectors.toList()));
            });
            //匹配一层数据 至根节点
            isRootList.forEach(a ->{
                a.setChapterDOS(notRootList1.stream().filter(b -> b.getParentId().equals(a.getId())).collect(Collectors.toList()));
            });
            page.setRecords(isRootList);
            page.setTotal(isRootList.size());
            if(request.getPaging() == 1){
                return Result.ok(isRootList);
            }else{
                return Result.ok(page);
            }
        }
        page.setRecords(list);
        page.setTotal(list.size());
        //验证是否分页
        if(request.getPaging() == 1){
            return Result.ok(list);
        }else{
            return Result.ok(page);
        }
    }

    @Override
    public Result updateCharpter(ChapterDO chapterDO) {
        //新增章节信息
        boolean aBoolean = this.updateById(chapterDO);
        if(aBoolean == false){
            return Result.fail();
        }
        documentService.delete(new EntityWrapper<ChapterDocument>().eq("chapter_id",chapterDO.getId()));
        boolean cBoolea = true;
        if(!chapterDO.getChapterDocuments().isEmpty()){
            //新增章节文件信息
            cBoolea = documentService.insertOrUpdateBatch(chapterDO.getChapterDocuments());
        }
        if (!cBoolea){
            return Result.fail();
        }
        return Result.ok();
    }


}
